package com.eas.yunzhijia.easTodo;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.cache.Cache;
import com.kingdee.shr.sso.client.ltpa.LtpaTokenManager;
import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;

@Service
public class TodoService {

    @Value("${shr.server.url}")
    String serverUrl;
    @Value("${shr.server.path}")
    String serverPath;
    @Value("${shr.auth.pattern}")
    String authPattern;

//    @Autowired
//    TPmEasxtusermapRepo tPmEasxtusermapRepo;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    OkHttpClient okHttpClient;

    @Autowired
    Cache<String, String> tokenCache;


    public String getToken() throws IOException, ExecutionException {
        return tokenCache.get("accessToken", () -> {
            Request.Builder requestBuilder = new Request.Builder();
            HttpUrl.Builder urlBuilder = new HttpUrl.Builder();
            //https://www.yunzhijia.com/gateway/oauth2/token/getAccessToken
            urlBuilder.scheme("https");
            urlBuilder.host("www.yunzhijia.com");
            urlBuilder.addPathSegment("gateway");
            urlBuilder.addPathSegment("oauth2");
            urlBuilder.addPathSegment("token");
            urlBuilder.addPathSegment("getAccessToken");
            requestBuilder.url(urlBuilder.build());
            System.out.println("url-----" + urlBuilder.build().url().toString());
            TokenEntity tokenEntity = new TokenEntity();
            tokenEntity.setAppId("500043950");
            tokenEntity.setScope("app");
            tokenEntity.setSecret("CloudHubJ2eeDemo");
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
            String time = df.format(new Date());
            long timestamp = df.parse(time).getTime();
            tokenEntity.setTimestamp(String.valueOf(timestamp));
            String body = objectMapper.writeValueAsString(tokenEntity);
            requestBuilder.post(RequestBody.create(MediaType.parse("application/json"), body));

            Response response = okHttpClient.newCall(requestBuilder.build()).execute();
            ResponseBody responseBody = response.body();
            if (response.isSuccessful() && responseBody != null) {
                TokenBody tokenBody = objectMapper.readValue(responseBody.byteStream(), TokenBody.class);
                System.out.println(tokenBody.isSuccess());
//                System.out.println("access_token---"+tokenBody.getData().getAccessToken());

                return tokenBody.getData().getAccessToken();
            } else {
                throw new IllegalArgumentException("appId或secret不正确");
            }
        });

    }

    public void sendPublicKey() throws IOException {

        Request.Builder builder = new Request.Builder();
        HttpUrl.Builder urlBuild = new HttpUrl.Builder();
        //https://www.yunzhijia.com/pubacc/pubsend
        urlBuild.scheme("https");
        urlBuild.host("www.yunzhijia.com");
        urlBuild.addPathSegment("pubacc");
        urlBuild.addPathSegment("pubsend");

        PublicMessageEntity entity = new PublicMessageEntity();
        entity.setType(5);
        PublicMessageEntity.FromBean fromBean = new PublicMessageEntity.FromBean();
        fromBean.setNo("8068716");
        fromBean.setNonce(UUID.randomUUID().toString());
        fromBean.setPub("XT-c86b3d8c-4ac7-4c93-a9d9-692433d430b2");

        fromBean.setTime(System.currentTimeMillis());

        String[] data = {"8068716", "XT-c86b3d8c-4ac7-4c93-a9d9-692433d430b2", "61ea1a660215aecc4addd789e488dba5", fromBean.getNonce(), String.valueOf(fromBean.getTime())};
        String pubToken = sha(data);
        fromBean.setPubtoken(pubToken);

        PublicMessageEntity.MsgBean msgBean = new PublicMessageEntity.MsgBean();
//        msgBean.setUrl("http://123.58.4.100:9999/getseach.html");
        msgBean.setUrl("http://123.58.4.100:9999/message/ticket");
        msgBean.setAppid("500043950");
        msgBean.setText("公共号测试");
        msgBean.setTodo(0);

        List<PublicMessageEntity.ToBean> toBeanList = new ArrayList<>();
        PublicMessageEntity.ToBean toBean = new PublicMessageEntity.ToBean();
        toBean.setNo("8068716");
        List<String> userList = new ArrayList<>();
        userList.add("5a9e3bfce4b032a2d1d40e93");
        toBean.setUser(userList);

        entity.setFrom(fromBean);
        entity.setMsg(msgBean);
        entity.setTo(toBeanList);
        String body = objectMapper.writeValueAsString(entity);
        builder.url(urlBuild.build());
        builder.post(RequestBody.create(MediaType.parse("application/json"), body));
        okHttpClient.newCall(builder.build()).execute();
    }

    public static String sha(String... data) {
        Arrays.sort(data);//按字母顺序排序数组
        return DigestUtils.sha1Hex(StringUtils.join(data));//把数组连接成字符串（无分隔符），并sha1哈希
    }

//    public String getOpenIdByNum(String number){
//        TPmEasxtusermapEntity entity = tPmEasxtusermapRepo.findOne((root, query, cb) ->
//                cb.equal(root.get(TPmEasxtusermapEntity_.fpersonnumber),number));
//        System.out.println("---number---"+entity.getFpersonnumber());
//        System.out.println("---personName---"+entity.getfPersonName());
//        System.out.println("----openid---"+entity.getfXtId());
//        System.out.println("---fid--"+entity.getFid());
//        System.out.println("---personId---"+entity.getfPersonId());
//        System.out.println("---fcell---"+entity.getfCell());
//        return entity.getfXtId();
//    }

    public String getOpenId(String ticket) throws IOException, ExecutionException {
        //https://www.yunzhijia.com/gateway/ticket/user/acquirecontext?accessToken=xxxxxx
        RequestContext context = new RequestContext();
        Request.Builder requestBuild = new Request.Builder();
        HttpUrl.Builder urlBuild = new HttpUrl.Builder();
        urlBuild.scheme("https");
        urlBuild.host("www.yunzhijia.com");
        urlBuild.addPathSegment("gateway");
        urlBuild.addPathSegment("ticket");
        urlBuild.addPathSegment("user");
        urlBuild.addPathSegment("acquirecontext");
        String accessToken = getToken();
        urlBuild.addQueryParameter("accessToken",accessToken);
        requestBuild.url(urlBuild.build());
        context.setTicket(ticket);
        context.setAppId("500043950");
        String body = objectMapper.writeValueAsString(context);
        requestBuild.post(RequestBody.create(MediaType.parse("application/json"), body));
        Response response = okHttpClient.newCall(requestBuild.build()).execute();
        ResponseBody responseBody = response.body();
        if (response.isSuccessful() && responseBody != null) {
            PersonContext personContext = objectMapper.readValue(responseBody.string(), PersonContext.class);
            return personContext.getData().getOpenid();
        } else {
            return null;
        }
    }


    public String getUserName(String openId) {
//        TPmEasxtusermapEntity entity = tPmEasxtusermapRepo.findOne((root, query, cb) ->
//                cb.equal(root.get(TPmEasxtusermapEntity_.fXtId), openId));
//        System.out.println("userNumber-------"+entity.getFpersonnumber());
//        return entity.getFpersonnumber();
        return "10017091";
    }

    public String buildRedirectUrl(String assignmentId){
        return "http://36.110.68.152:6888/easweb/webviews/workflow/approve.jsp?assignmentId="+assignmentId;
    }


    URL login(String username, String redirectTo) {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(serverUrl).newBuilder();
        urlBuilder.addPathSegment(serverPath);
        urlBuilder.addQueryParameter("password", LtpaTokenManager.generate(username, LtpaTokenManager.getDefaultLtpaConfig(), authPattern).toString());
        urlBuilder.addQueryParameter("username", username);
        urlBuilder.addQueryParameter("redirectTo", redirectTo);
        System.out.println("redirectUrl-------------" + String.valueOf(urlBuilder.build().url()));
        return urlBuilder.build().url();
    }

    String login2(String userName,String rediretTo){
        String s = serverUrl+"/"+serverPath+"?password="+LtpaTokenManager.generate(userName, LtpaTokenManager.getDefaultLtpaConfig()).toString()+"&username="+userName+"&redirectTo="+rediretTo;
        System.out.println("url-----------"+s);
        return s;
    }

    public String buildAssignmentPageSSOLink(String ticket,String assignmentId) throws IOException, ExecutionException {
        String openId = getOpenId(ticket);
        String userName = getUserName(openId);
        String redirectUrl = buildRedirectUrl(assignmentId);
        return login2(userName,redirectUrl);
    }



}
